package com.jajahome.pop;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

/**
 * PopupWindow 基类，用于居中显示的PopupWindow
 * Created by lhz.
 * Date: 2020-06-24
 * Time: 22:02
 */
public abstract class BasePopWindow extends PopupWindow {
    final float ALPHA = 0.6f;
    protected final Activity mActivity;
    protected View mRootView;


    public BasePopWindow(final Activity activity) {
        this.mActivity = activity;
        //消失时取消透明度设置
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp1 = mActivity.getWindow().getAttributes();
                lp1.alpha = 1f;
                mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                mActivity.getWindow().setAttributes(lp1);
            }
        });
        initPopWindow();
    }

    public void show() {
        View view = mActivity.getWindow().getDecorView();
        mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        backgroundAlpha();
        showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    // 设置屏幕透明度
    public void backgroundAlpha() {
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 0.4f; //设置透明度
        mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        mActivity.getWindow().setAttributes(lp);

    }

    private void initPopWindow() {
        LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mRootView = inflater.inflate(getLayoutId(), null);
        this.setContentView(mRootView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(getWidth());
        // 设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(getHeight());
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        this.setOutsideTouchable(false);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        // 设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        initView();

    }

    public abstract int getLayoutId();
    public abstract int getWidth();
    public abstract int getHeight();
    public abstract void initView();
}
